package org.finesys.ai.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.finesys.ai.entity.AigcEmbedStore;
import org.finesys.ai.mapper.AigcEmbedStoreMapper;
import org.finesys.ai.service.AigcEmbedStoreService;
import org.finesys.chat.core.base.constants.EventTypeEnum;
import org.finesys.chat.core.base.events.EmbeddingStoreEvent;
import org.finesys.common.core.util.SpringContextHolder;
import org.finesys.common.mp.core.service.impl.BaseServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

@Service
@Slf4j
public class AigcEmbedStoreServiceImpl extends BaseServiceImpl<AigcEmbedStoreMapper, AigcEmbedStore> implements AigcEmbedStoreService {


    @Override
    public boolean saveEmbedStore(AigcEmbedStore embedStore) {
        this.save(embedStore);
        sendEvent(embedStore, EventTypeEnum.ADD.getName());
        return true;
    }

    @Override
    public boolean updateEmbedStore(AigcEmbedStore embedStore) {
        this.updateById(embedStore);
        sendEvent(embedStore, EventTypeEnum.UPDATE.getName());
        return true;
    }

    @Override
    public boolean deleteEmbedStore(String[] ids) {
        if (ids == null || ids.length == 0) {
            return false;
        }
        List<AigcEmbedStore> list = this.listByIds(Arrays.asList(ids));
        list.stream().forEach(item -> {
            this.removeById(item.getId());
            sendEvent(item, EventTypeEnum.DELETE.getName());
        });
        return false;
    }

    private void sendEvent(AigcEmbedStore item, String type) {
        EmbeddingStoreEvent event = new EmbeddingStoreEvent(item, type);
        boolean send = SpringContextHolder.publishEvent(event);
        if (!send) {
            if (log.isWarnEnabled()) {
                log.warn(String.format("向量数据库事件[%s]发送失败", item));
            }
        }
    }
}
